package server;

import util.MyClassLoad;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.util.List;
import java.util.Map;

// 将请求任务交由线程去执行
public class RequestProcessor extends Thread {

    private Socket socket;

    private Mapper mapper;
    public RequestProcessor(Socket socket, Mapper mapper){
        this.socket = socket;
        this.mapper = mapper;
    }

    /*private Map<String, HttpServlet> servletMap;
    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap){
        this.servletMap = servletMap;
        this.socket = socket;
    }*/


    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            // 封装成的输入对象
            Request request = new Request(inputStream);
            // 封装成的输出对象
            Response response = new Response(socket.getOutputStream());

            // 动、静资源 的访问
            if(getServlet(request.getUrl()) == null){
                response.outputHtml(request.getUrl());
            } else {
                HttpServlet httpServlet = getServlet(request.getUrl());
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private HttpServlet getServlet(String url){
        //String url  : /web_demo/test/info
        String contextUrl = url.split("/")[1];

        if (mapper.getMappedContext(contextUrl) == null){
            return null;
        }

        String wrapperUrl = url.replace(contextUrl, "").substring(1);
        Mapper.MappedContext mappedContext = mapper.getMappedContext(contextUrl);
        List<Mapper.MappedWrapper> wrapperList = mappedContext.getWrapperList();
        for (Mapper.MappedWrapper mappedWrapper : wrapperList){
            if (mappedWrapper.getWrapperUrl().equalsIgnoreCase(wrapperUrl)){
                HttpServlet httpServlet = mappedWrapper.getHttpServlet();
                return httpServlet;
            }
        }

        return null;
    }

}
